<?php
	class url{
		private $currentRequest = null;
		private $currentClass = null;
		private $currentMethod = null;
		private $isModule = false;
		private $module = null;
		public $request = null;
		public function __construct(){
			$this->request = $_GET;
			if(!empty($this->request['r'])){
				systemGlobals::$currentRequest = $this->request['r'];
			}else{
				systemGlobals::$currentRequest = systemConfig::$baseUrl;
			}
		}
		
		public function readUrl(){
			if(empty($this->request['r'])){
				include_once 'system/config/main.php';
				$this->request['r'] = systemConfig::$baseUrl;
			}
			$r = explode("/", $this->request['r']);
			$checkRequest = count($r);
			if($checkRequest==2 || $checkRequest==3){
				// check if request is a module
				if($checkRequest==3){
					$this->isModule=true;
					$this->module='module/'.$r[0];
					systemGlobals::$moduleName = $r[0];
					$r[0]=$r[1];
					$r[1]=$r[2];
					systemGlobals::$module=$this->module;
				}else{
					systemGlobals::$module=null;
				}
				// calling a controller
				 if($this->checkClass($r[0])){
					 if(method_exists($this->currentClass, $r[1])){
					 	try {
					 		// setting method
					 		$this->currentMethod=$r[1];
					 		// setting systemGlobal vars
					 		systemGlobals::$folder=$r[0];
					 		systemGlobals::$file=$r[1];
					 		// get action method
					 		$refInvoke = new ReflectionMethod($this->currentClass, $this->currentMethod);
					 		// method new instance 
					 		$toRun = new $this->currentClass;
					 		// check auth
					 		webUser::authenticationRedirect();
					 		// run action
					 		echo $refInvoke->invoke($toRun, "");
					 		// return values to default.
					 		systemGlobals::$module=null;
					 		systemGlobals::$moduleName=null;
					 		systemGlobals::$folder=null;
					 		systemGlobals::$file=null;
					 	} catch (Exception $e) {
					 		$refInvoke = new ReflectionMethod("errorController", "error404");
					 		echo $refInvoke->invoke(new errorController(), "");
					 	}
					 }else{
					 	$refInvoke = new ReflectionMethod("errorController", "error404");
					 	echo $refInvoke->invoke(new errorController(), "");
					 }
				 }else{
				 	$refInvoke = new ReflectionMethod("errorController", "error404");
					echo $refInvoke->invoke(new errorController(), "");
				 }
			}else{
				$refInvoke = new ReflectionMethod("errorController", "error404");
				echo $refInvoke->invoke(new errorController(), "");
			}
		}
		public function checkClass($className){
			try {
				$module = null;
				$className=$className."Controller";
				systemGlobals::checkContent('system/'.$this->module.'/controller/'.$className.'.php');
				include_once 'system/'.$this->module.'/controller/'.$className.'.php';
				if(class_exists($className)){
					$this->currentClass = $className;
					return true;
				}else{
					return false;
				}
			} catch (Exception $e) {
				return false;
			}
		}
	}